package com.wsapi.core.auth;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.wsapi.core.dao.model.SysRole;
import com.wsapi.core.service.AccountService;
import org.apache.shiro.SecurityUtils;

@Component
public class DbRealm extends AuthorizingRealm {

    private AccountService accountService;

    @Resource
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String accId = (String) principals.getPrimaryPrincipal();
        if (accId != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Set<SysRole> roles = this.accountService.getAccountRoles(accId);
            if (roles != null) {
                for (SysRole role : roles) {
                    info.addRole(role.getRoleName());
                }
            }
            Set<String> permissions = this.accountService
                    .getAccountPermissions(accId);
            if (permissions != null) {
                for (String perm : permissions) {
                    info.addStringPermission(perm);
                }
            }
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordCaptchaToken token2 = (UsernamePasswordCaptchaToken) token;
        String accId = this.accountService.checkLogin(token2.getUsername(),
                String.valueOf(token2.getPassword()));
        if (accId == null) {
            return null;
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(accId,
                token2.getPassword(), this.getName());
        return info;
    }

}
